package com.yuanrui.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.base.Preconditions;
import com.yuanrui.auth.application.util.LoginUtil;
import com.yuanrui.auth.entity.AuthUserDTO;
import com.yuanrui.auth.application.convert.AuthUserConverter;
import com.yuanrui.auth.common.entity.Result;
import com.yuanrui.auth.domain.entity.AuthUserBO;
import com.yuanrui.auth.domain.service.AuthUserDomainService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user/")
@Slf4j
public class UserController {
    @Resource
    private AuthUserDomainService authUserDomainService;

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录结果
     */
//    @RequestMapping("loginByPwd")
//    public SaResult doLogin(String username, String password) {
//        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
//        if ("zhang".equals(username) && "123456".equals(password)) {
//            StpUtil.login(17);
//            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
//            return SaResult.data(tokenInfo);
//        }
//        return SaResult.error("登录失败");
//    }

    /**
     * 批量获取用户信息
     */
    @RequestMapping("listByIds")
    public Result<List<AuthUserDTO>> listUserInfoByIds(@RequestBody List<String> userNameList) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.listUserInfoByIds.dto:{}", JSON.toJSONString(userNameList));
            }
            Preconditions.checkArgument(!CollectionUtils.isEmpty(userNameList), "id集合不能为空");
            List<AuthUserBO> userInfos = authUserDomainService.listUserInfoByIds(userNameList);
            return Result.ok(AuthUserConverter.INSTANCE.convert(userInfos));
        } catch (Exception e) {
            log.error("UserController.listUserInfoByIds.error:{}", e.getMessage(), e);
            return Result.fail("批量获取用户信息失败");
        }
    }

    /**
     * 通过微信验证码登录
     */
    @RequestMapping("doLogin")
    public Result<SaTokenInfo> doLogin(String validCode) {
        try {
            Preconditions.checkArgument(StringUtils.isNotBlank(validCode), "验证码不能为空");
            // 此处仅作模拟示例，真实项目需要通过code获取用户信息
            SaTokenInfo saTokenInfo = authUserDomainService.doLogin(validCode);
            return Result.ok(saTokenInfo);
        } catch (Exception e) {
            return Result.fail("登录失败");
        }
    }

    /**
     * 注册接口
     *
     * @param authUserDTO 用户信息
     * @return 注册结果
     */
    @RequestMapping("register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.register.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getUserName(), "用户名不能为空");
            Preconditions.checkNotNull(authUserDTO.getPassword(), "密码不能为空");
            Preconditions.checkNotNull(authUserDTO.getPhone(), "手机号不能为空");
            Preconditions.checkNotNull(authUserDTO.getEmail(), "邮箱不能为空");
            Preconditions.checkNotNull(authUserDTO.getNickName(), "给自己取一个昵称吧");
            AuthUserBO authUserBO = AuthUserConverter.INSTANCE.convert(authUserDTO);
            authUserDomainService.addUser(authUserBO);
            return Result.ok(true);
        } catch (Exception e) {
            log.error("UserController.register.error:{}", e.getMessage(), e);
            return Result.fail("注册失败");
        }
    }

    /**
     * 修改用户信息
     */
    @RequestMapping("update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getUserName(), "用户名不能为空");
            AuthUserBO authUserBO = AuthUserConverter.INSTANCE.convert(authUserDTO);
            authUserDomainService.update(authUserBO);
            return Result.ok(true);
        } catch (Exception e) {
            log.error("UserController.update.error:{}", e.getMessage(), e);
            return Result.fail("更新用户信息失败");
        }
    }

    /**
     * 删除   户信息
     */
    @RequestMapping("delete")
    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getId(), "用户ID不能为空");
            AuthUserBO authUserBO = AuthUserConverter.INSTANCE.convert(authUserDTO);
            authUserDomainService.delete(authUserBO);
            return Result.ok(true);
        } catch (Exception e) {
            log.error("UserController.update.error:{}", e.getMessage(), e);
            return Result.fail("删除用户信息失败");
        }
    }

    /**
     * 用户启用/禁用
     */
    @RequestMapping("changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getStatus(), "用户状态不能为空");
            AuthUserBO authUserBO = AuthUserConverter.INSTANCE.convert(authUserDTO);
            authUserDomainService.update(authUserBO);
            return Result.ok(true);
        } catch (Exception e) {
            log.error("UserController.update.error:{}", e.getMessage(), e);
            return Result.fail("更新用户信息失败");
        }
    }

    @RequestMapping("getUserInfo")
    public Result<AuthUserDTO> getUserInfo(@RequestBody AuthUserDTO authUserDTO) {
        log.info("loginId:{}", LoginUtil.getLoginId());
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.getUserInfo.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getUserName(), "用户名不能为空");
            AuthUserBO authUserBO = AuthUserConverter.INSTANCE.convert(authUserDTO);
            AuthUserBO user = authUserDomainService.getUserInfo(authUserBO);
            AuthUserDTO userDTO = AuthUserConverter.INSTANCE.convert(user);
            return Result.ok(userDTO);
        } catch (Exception e) {
            log.error("UserController.getUserInfo.error:{}", e.getMessage(), e);
            return Result.fail("查询用户信息失败");
        }
    }

    /**
     * 用户登出
     */
    @RequestMapping("logOut")
    public Result logout(@RequestParam String userName) {
        try {
            log.info("UserController.logout.userName:{}", userName);
            StpUtil.logout(userName);
            return Result.ok(true);
        } catch (Exception e) {
            log.error("UserController.logout.error:{}", e.getMessage(), e);
            return Result.fail("登出失败");
        }
    }
}
